<?php
/**
 * Created by PhpStorm.
 * User: HP_USER
 * Date: 2018/6/7
 * Time: 15:42
 */


namespace app\admin\controller;

use app\common\Common;
use app\data\AdminData;
use app\data\ProxyDate;
use app\index\controller\User;
use think\Db;

class Platform extends Base
{
    private $specialProvince = [110000, 120000, 310000, 500000];

    /**
     * 平台手续费显示
     * @return \think\response\Json
     */
    public function feesStatistics()
    {
        $time = time();
        $week_time = Common::getStarEndTime($time);
        $end_time = date('Y-m-d', $time);
        $start_time = date('Y-m-d', $week_time['start']);
        $admin = new AdminData();
        $platform_info = $admin->getPlatformInfo();
        $total_money = $platform_info['total_platform_money'] + $platform_info['total_fees_money'];
        $today_money = $admin->getTotalFees("create_time >={$end_time} and create_time <={$time} and money_expenses > 0");
        $moth_money = $admin->getTotalFees("create_time >={$end_time} and create_time <={$time} and money_expenses > 0");
        $list= $admin->getFees($start_time, $end_time);
        return json([
            'code' => $this->t_code,
            'msg' => 'OK',
            'data' => [
                'list' =>$list,
                'total_money' => $total_money,
                'today_money' => empty($today_money['money']) ? 0 : $today_money['money'],
                'moth_money' => empty($moth_money['money']) ? 0 : $moth_money['money']
            ]
        ]);
    }

    /**
     * 添加区域代理
     * @param $user_id
     * @param $type_lv
     * @param $area_id
     * @return \think\response\Json
     */
    public function addProxy($user_id, $type_lv, $area_id)
    {
        if (Common::checkTableFields('drh_user_info', 'id', $user_id) == $this->f_code) {
            return json(['code' => $this->f_code, 'msg' => '不存在该用户']);
        }
        $id = Common::getTableValue('drh_proxy', 'id', 'user_id', $user_id);
        if (!empty($id)) {
            return json(['code' => $this->f_code, 'msg' => '每人只能有一个代理身份']);
        }
        if ($type_lv != 0 && $type_lv != 1 && $type_lv != 2) {
            return json(['code' => $this->f_code, 'msg' => '代理级别错误']);
        }
        if ($type_lv != 0) {//不是全国代理
            $id = Common::getTableValue('china_area', 'id', ['id', 'area_level'], [$area_id, $type_lv - 1]);
            if (empty($id)) {
                return json(['code' => $this->f_code, 'msg' => '不存在该区域']);
            }
        } else {
            $id = Common::getTableValue('drh_proxy', 'user_id', 'area_id', 0);
            if (!empty($id)) {
                return json(['code' => $this->f_code, 'msg' => '全国代理只能有一个']);
            }
            $area_id = 0;
        }
        $admin = new AdminData();
        return json($admin->addProxy($user_id, $type_lv, $area_id));
    }

    /**
     * 省代
     * @param $type_lv
     * @return bool|\think\response\Json
     */
    public function showProvince($type_lv)
    {
        $proxy_data = new ProxyDate();
        $res = $proxy_data->getAreaInfo($type_lv);
        switch ($type_lv) {
            case  1://省代
                return json(['code' => $this->t_code, 'msg' => 'ok', 'data' => $this->removalProvince($res, $proxy_data)]);
            case  2://市代
                return json(['code' => $this->t_code, 'msg' => 'ok', 'data' => $res]);
            default :
                return true;
        }
    }

    /**
     * 去除已经代理的省份
     * @param $res
     * @param ProxyDate $proxy_data
     * @return array
     */
    private function removalProvince($res, ProxyDate $proxy_data)
    {
        $info = $proxy_data->getProxyAreaInfo(" a.type_lv=1 and a.recover_status=0 ");
        $area = [];
        foreach ($res as $v) {
            $area[$v['name']] = $v['id'];
        }
        $proxy = [];
        foreach ($info as $v) {
            $proxy[$v['name']] = $v['id'];
        }
        $arr = array_diff($area, $proxy);
        $return_arr = [];
        foreach ($arr as $k => $v) {
            $return_arr[] = ['name' => $k, 'id' => $v];
        }
        return $return_arr;
    }

    /**
     * 市代
     * @param $p_id
     * @return \think\response\Json
     */
    public function showMunicipal($p_id)
    {
        if (in_array($p_id, $this->specialProvince)) {
            return json(['code' => $this->t_code, 'msg' => '直辖市没有市代']);
        }
        $proxy_data = new ProxyDate();
        $res = $proxy_data->getAreaInfo(2, $p_id);
        return json([
            'code' => $this->t_code,
            'msg' => 'OK',
            'data' => $this->removalMunicipal($p_id, $res, $proxy_data)
        ]);
    }

    /**
     * 去除已经代理的市
     * @param $p_id
     * @param $res
     * @param ProxyDate $proxy_data
     * @return array
     */
    private function removalMunicipal($p_id, $res, ProxyDate $proxy_data)
    {
        $info = $proxy_data->getProxyAreaInfo(" b.parent_id={$p_id} and a.recover_status=0 ");
        $area = [];
        foreach ($res as $v) {
            $area[$v['name']] = $v['id'];
        }
        $proxy = [];
        foreach ($info as $v) {
            $proxy[$v['name']] = $v['id'];
        }
        $arr = array_diff($area, $proxy);
        $return_arr = [];
        foreach ($arr as $k => $v) {
            $return_arr[] = ['name' => $k, 'id' => $v];
        }
        return $return_arr;
    }

    /**
     * 代理统计图
     * @return \think\response\Json
     */
    public function showCommission()
    {
        $time = time();
        $day_start = (date('Y-m-d', $time));
        $arr = explode('-', $day_start);
        $day = $arr[2];//获取天数
        $month = $arr[1];//获取月份
        if ($day == '01') {
            if ($month == '01') {
                $month_start = strtotime(($arr[0] - 1) . '-12-02');
            } else {
                $month_start = strtotime($arr[0] . '-' . ($arr[1] - 1) . '-02');
            }
        } else {
            $month_start = strtotime($arr[0] . '-' . $arr[1] . '-02');
        }
        $day_start = strtotime($day_start);
        $proxy = new ProxyDate();
        $data['day_province'] = $proxy->getProxyMoney(" create_time>={$day_start} and create_time <{$time} and type_status=1");
        $data['month_province'] = $proxy->getProxyMoney(" create_time>={$month_start} and create_time <{$time} and type_status=1");
        $data['day_municipal'] = $proxy->getProxyMoney(" create_time>={$day_start} and create_time <{$time} and type_status=2");
        $data['month_municipal'] = $proxy->getProxyMoney(" create_time>={$month_start} and create_time <{$time} and type_status=2");
        return json([
            'code' => $this->t_code,
            'msg' => 'OK',
            'data' => $data
        ]);
    }

    /**
     * 搜索区域代理
     * @param $user_tel
     * @return \think\response\Json
     */
    public function searchProxy($user_tel)
    {
        $user = new User();
        $res = $user->searchProxy($user_tel);
        if ($res['code'] = $this->f_code) {
            return json($res);
        }
        $res['data']['user_tel'] = $user_tel;
        $res['data']['month_province'] = $this->getOneProxyMoney($res['data']['user_id']);
        $res['data']['province'] = Common::getTableValue('drh_admin_config', 'value', 'name', 'province');
        $res['data']['municipal'] = Common::getTableValue('drh_admin_config', 'value', 'name', 'municipal');
        return json([
            'code' => $this->t_code,
            'msg' => 'OK',
            'data' => $res['data']
        ]);
    }

    public function getOneProxyMoney($user_id)
    {
        $time = time();
        $day_start = (date('Y-m-d', $time));
        $arr = explode('-', $day_start);
        $day = $arr[2];//获取天数
        $month = $arr[1];//获取月份
        if ($day == '01') {
            if ($month == '01') {
                $month_start = strtotime(($arr[0] - 1) . '-12-02');
            } else {
                $month_start = strtotime($arr[0] . '-' . ($arr[1] - 1) . '-02');
            }
        } else {
            $month_start = strtotime($arr[0] . '-' . $arr[1] . '-02');
        }
        $proxy = new ProxyDate();
        $data['month_province'] = $proxy->getProxyMoney(" 
        create_time>={$month_start} 
        and 
        create_time <{$time} 
        and 
        type_status=1
        and 
        user_id={$user_id} ");
        return $data['month_province'];
    }

    /**
     * 手续费
     * @return \think\response\Json
     */
    public function showFeesConfig()
    {
        return json([
            'code' => $this->t_code,
            'msg' => 'OK',
            'data' => Common::getTableValue('drh_admin_config', 'value', 'name', 'fees')
        ]);
    }

    /**
     * 代理分佣比例
     * @return \think\response\Json
     */
    public function showProxy()
    {
        return json([
            'code' => $this->t_code,
            'msg' => 'OK',
            'data' => [
                'province' => Common::getTableValue('drh_admin_config', 'value', 'name', 'province'),
                'municipal' => Common::getTableValue('drh_admin_config', 'value', 'name', 'municipal')
            ]
        ]);
    }

    /**
     * 修改配置
     * @param $name
     * @param $change_value
     * @return \think\response\Json
     */
    public function editConfig($name, $change_value)
    {
        $time = time();
        if (!Common::checkNumber($change_value)) {
            return json(['code' => $this->f_code, 'msg' => '参数错误']);
        }
        if ($change_value > 100 && $name != 'fees') {
            return json(['code' => $this->f_code, 'msg' => '参数错误']);
        }
        $proxy = new ProxyDate();
        Db::startTrans();
        try {
            $proxy->editConfig($name, $change_value);
            $proxy->addFlowConfig($name,
                $change_value,
                $time,
                Common::getTableValue('drh_admin_config', 'value', 'name', $name));
            Db::commit();
            return json(['code' => $this->t_code, 'msg' => '修改成功']);
        } catch (\Exception $e) {
            Db::rollback();
            return json(['code' => $this->f_code, 'msg' => $e->getMessage()]);
        }
    }

}